import React from 'react';
import './index.less';
import axios from 'axios';
import statuscode from '../../statuscode/index';
import { Input, Button, Table, Pagination, Modal } from 'antd';
import Invite from '../invite/index';
import Detail from '../detail/index';
import Approvaldetail from '../approvaldetail/index';
import Tips from '../../Tips/index';
import { connect } from 'react-redux';
import Bread from '../../common/Bread/index';
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8';

var networkstatus = {
  0: '待审批',
  1000: '通过',
  1010: '拒绝',
};
class ApprovalRecord extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      visibility: false,
      data: [],
      value: 1,
      limit: 10,
      page: 1
    };
  }
  componentWillMount() {
    this.ismounted = true;
    this.getData(this.state.page, this.state.limit);
  }
  componentWillUpdate(next) {
    if (next.clickNetwork != this.props.clickNetwork || next.changeOrgid != this.props.changeOrgid) {
      this.getData(this.state.page, this.state.limit, next.changeOrgid, next.clickNetwork);
    }
  }
  componentWillUnmount() {
    this.ismounted = false;
  }
  setData = {
    page: ['10', '20', '30', '40', '50', '60', '70', '80', '90']
  }
  columnsInvite = [{
    title: '组织名称',
    dataIndex: '组织名称',
    key: '组织名称',
    render: (text, i) => <span onClick={this.approvaldetailshowModal.bind(this, text, i)} >{text}</span>,
  }, {
    title: '网络',
    dataIndex: '网络',
    key: '网络',
    render: (text, i) => <span onClick={this.detailshowModal.bind(this, text, i)} >{text}</span>,
  }, {
    title: '状态',
    dataIndex: '状态',
    key: '状态',
  }, {
    title: '申请提交时间',
    dataIndex: '申请提交时间',
    key: '申请提交时间',
    sortOrder: 'descend'
  }, {
    title: '审批完成时间',
    dataIndex: '审批完成时间',
    key: '审批完成时间',
  }, {
    title: '操作',
    key: '操作',
    width: 200,
    render: (text, i) => (
      <span className="approvalbox">
        <span onClick={this.handleComfirm.bind(this, text)} style={{ marginRight: 10 }} className={i['状态'] != '待审批' ? 'disablednone' : ''} >
          通过
        </span>
        <span onClick={this.handleRefuse.bind(this, text)} className={i['状态'] != '待审批' ? 'disablednone' : ''} >
          拒绝
        </span>
      </span>
    )
  }];
stateData = {
  page: ['10', '20', '30', '40', '50', '60', '70', '80', '90']
}
  InviteUser = () => {
    this.setState({
      visibility: true,
    });
  }
  handleCancel = () => {
    this.setState({
      visiblepass: false,
      visiblereject: false,
      visiblestartnet: false,
      visiblestopnet: false,
      joinnet: false
    });
  }
  inviteshowModal = (text) => {
    const Token = localStorage.getItem('token');
    this.setState({
      message: 'loading'
    });
    const _this = this;
    axios({
      method: 'get',
      url: '/api/block/network/queryBaasNetworkByAdmin',
      headers: {
        'Content-Type': 'application/json',
        Authorization: Token
      },
      params: { networkName: this.props.clickNetwork }
    })
      .then(function (response) {
        if (_this.ismounted) {
          var code = response.data.code;
          if (statuscode[response.data.code] == undefined) code = '500';
          var message = statuscode[code];
          if (code == 200) {
            _this.setState({
              invitevisible: true,
              detailvisible: false,
              invitationdata: response.data.data,
              message: message,
              visiblepass: false,
              visiblereject: false
            }, () => {
              setTimeout(() => {
                _this.setState({
                  message: ''
                });
              }, 1000);
            });
          } else {
            _this.setState({
              // detailvisible: false,
              message: message
            }, () => {
              setTimeout(() => {
                _this.setState({
                  message: ''
                });
              }, 1000);
            });
          }
        }
      })
      .catch(function (error) {
        console.log(error);
        if (_this.ismounted) {
          _this.setState({
            message: '请求失败，请刷新重试'
          }, () => {
            setTimeout(() => {
              _this.setState({
                message: ''
              });
            }, 1000);
          });
        }
      });
  }
  invitehandleChancel = () => {
    this.setState({
      invitevisible: false,
    });
  }
  detailshowModal = (text, i) => {
    const Token = localStorage.getItem('token');
    var _this = this;
    axios({
      method: 'get',
      url: '/api/block/network/queryBaasNetwork',
      headers: {
        'Content-Type': 'application/json',
        Authorization: Token
      },
      params: { networkName: i['网络'] }
    })
      .then(function (response) {
        if (_this.ismounted) {
          var code = response.data.code;
          if (statuscode[response.data.code] == undefined) code = '500';
          var message = statuscode[code];
          _this.setState({
            detailvisible: true,
            title: text,
            detaildata: response.data.data,
            message: message
          }, () => {
            setTimeout(() => {
              _this.setState({
                message: ''
              });
            }, 1000);
          });
        }
      })
      .catch(function (error) {
        console.log(error);
        if (_this.ismounted) {
          _this.setState({
            message: '请求失败，请刷新重试'
          }, () => {
            setTimeout(() => {
              _this.setState({
                message: ''
              });
            }, 1000);
          });
        }
      });
  }
  detailhandleChancel = () => {
    this.setState({
      detailvisible: false,
    });
  }

  approvaldetailshowModal = (text, i) => {
    var _this = this;
    this.setState({
      message: 'loading',
      textdata: i
    });
    const Token = localStorage.getItem('token');
    axios({
      method: 'get',
      url: '/api/block/network/queryBaasNetworkOrgApply?id=' + i.applyId,
      headers: {
        'Content-Type': 'application/json',
        Authorization: Token
      },
    })
      .then(function (response) {
        if (_this.ismounted) {
          var code = response.data.code;
          if (statuscode[response.data.code] == undefined) code = '500';
          var message = statuscode[code];
          _this.setState({
            approvaldetailvisible: true,
            title: text,
            approvaldetaildata: response.data.data,
            approvaledstatus: i['状态'],
            message: message
          }, () => {
            setTimeout(() => {
              _this.setState({
                message: ''
              });
            }, 1000);
          });
        }
      })
      .catch(function (error) {
        console.log(error);
        if (_this.ismounted) {
          _this.setState({
            message: '请求失败，请刷新重试'
          }, () => {
            setTimeout(() => {
              _this.setState({
                message: ''
              });
            }, 1000);
          });
        }
      });
  }
  approvaldetailhandleChancel = () => {
    this.setState({
      approvaldetailvisible: false,
    });
  }

  pass = () => {
    this.setState({
      message: 'loading'
    });
    const Token = localStorage.getItem('token');
    var data = {
      networkName: this.props.clickNetwork, orgId: this.props.changeOrgid, applyId: this.state.textdata.applyId
    };
    var _this = this;
    axios.post('/api/block/network/approveNetworkOrgPass', data, {
      headers: {
        'Content-Type': 'application/json',
        Authorization: Token
      }
    })
      .then(function (response) {
        if (_this.ismounted) {
          var code = response.data.code;
          if (statuscode[response.data.code] == undefined) code = '500';
          var message = statuscode[code];
          _this.setState({
            message: message
          }, () => {
            setTimeout(() => {
              if (code == 200) {
                _this.getData(_this.state.page, _this.state.limit);
                _this.setState({
                  message: '',
                  detailvisible: false,
                  visiblepass: false,
                });
              } else {
                _this.setState({
                  message: '',
                });
              }
            }, 1000);
          });
        }
      })
      .catch(function (error) {
        console.log(error);
        if (_this.ismounted) {
          _this.setState({
            message: '请求失败，请刷新重试'
          }, () => {
            setTimeout(() => {
              _this.setState({
                message: ''
              });
            }, 1000);
          });
        }
      });
  }
  reject = () => {
    this.setState({
      message: 'loading'
    });
    const Token = localStorage.getItem('token');
    var data = {
      networkName: this.props.clickNetwork, orgId: this.props.changeOrgid, applyId: this.state.textdata.applyId
    };
    var _this = this;
    axios.post('/api/block/network/approveNetworkOrgDeny', data, {
      headers: {
        'Content-Type': 'application/json',
        Authorization: Token,
      }
    })
      .then(function (response) {
        if (_this.ismounted) {
          var code = response.data.code;
          if (statuscode[response.data.code] == undefined) code = '500';
          var message = statuscode[code];
          _this.setState({
            message: message
          }, () => {
            setTimeout(() => {
              if (code == 200) {
                _this.getData(_this.state.page, _this.state.limit);
                _this.setState({
                  message: '',
                  detailvisible: false,
                  visiblereject: false
                });
              } else {
                _this.setState({
                  message: '',
                });
              }
            }, 1000);
          });
        }
      })
      .catch(function (error) {
        console.log(error);
        if (_this.ismounted) {
          _this.setState({
            message: '请求失败，请刷新重试'
          }, () => {
            setTimeout(() => {
              _this.setState({
                message: ''
              });
            }, 1000);
          });
        }
      });
  }
  stopnetvisble = (text, i) => {
    this.setState({
      visiblestopnet: true,
      textdatanet: text
    });
  }
  startnetvisble = (text, i) => {
    if (text['状态'] == '启动成功' || i == '启动成功') return;
    this.setState({
      visiblestartnet: true,
      textdatanet: text
    });
  }
  start = () => {
    var text = this.state.textdatanet;
    this.setState({
      message: 'loading'
    });
    var _this = this;
    const Token = localStorage.getItem('token');
    var networkName = text.networkname ? text.networkname : text;
    var data = {
      networkName: networkName, orgId: this.props.changeOrgid
    };
    axios.post('/api/block/network/startNetWork', data, {
      headers: {
        'Content-Type': 'application/json',
        Authorization: Token,
      }
    })
      .then(function (response) {
        if (_this.ismounted) {
          var code = response.data.code;
          if (statuscode[response.data.code] == undefined) code = '500';
          var message = statuscode[code];
          _this.setState({
            message: message
          }, () => {
            setTimeout(() => {
              if (code == 200) {
                _this.getData(_this.state.page, _this.state.limit);
                _this.setState({ visiblestartnet: false });
              }
              _this.setState({
                message: '',
              });
            }, 1000);
          });
        }
      })
      .catch(function (error) {
        console.log(error);
        if (_this.ismounted) {
          _this.setState({
            message: '请求失败，请刷新重试'
          }, () => {
            setTimeout(() => {
              _this.setState({
                message: ''
              });
            }, 1000);
          });
        }
      });
  }

  stop = () => {
    var text = this.state.textdatanet;
    this.setState({
      message: 'loading'
    });
    const Token = localStorage.getItem('token');
    var networkName = text.networkname ? text.networkname : text;
    var data = {
      networkName: networkName, orgId: this.props.changeOrgid
    };
    var _this = this;
    axios.post('/api/block/network/stopNetWork', data, {
      headers: {
        'Content-Type': 'application/json',
        Authorization: Token,
      }
    })
      .then(function (response) {
        if (_this.ismounted) {
          var code = response.data.code;
          if (statuscode[response.data.code] == undefined) code = '500';
          var message = statuscode[code];
          _this.setState({
            message: message
          }, () => {
            setTimeout(() => {
              if (code == 200) {
                _this.getData(_this.state.page, _this.state.limit);
                _this.setState({ visiblestopnet: false });
              }
              _this.setState({
                message: '',
              });
            }, 1000);
          });
        }
      })
      .catch(function (error) {
        console.log(error);
        if (_this.ismounted) {
          _this.setState({
            message: '请求失败，请刷新重试'
          }, () => {
            setTimeout(() => {
              _this.setState({
                message: ''
              });
            }, 1000);
          });
        }
      });
  }



  searchchange= (ev) => {
    this.setState({ searchvalue: ev.target.value });
  }
  search = (ev) => {
    this.getData(this.state.page, this.state.limit, this.props.changeOrgid, this.props.clickNetwor, this.state.searchvalue);
  }

  handleComfirm = (text) => {
  // 此处填写申请通过交互
    if (text['状态'] != '待审批') return;
    this.setState({
      visiblepass: true,
      textdata: text
    });
  }
    handleRefuse = (text) => {
      // 此处填写申请拒绝交互
      if (text['状态'] != '待审批') return;
      this.setState({
        visiblereject: true,
        textdata: text
      });
    }
  onShowSizeChange = (current, pageSize) => {
    this.getData(current, pageSize);
    this.setState({
      limit: pageSize,
      page: current
    });
  }
  onChange = (pageNumber) => {
    this.getData(pageNumber);
  }
  stopnetvisble = (text, i) => {
    this.setState({
      visiblestopnet: true,
      textdatanet: text
    });
  }
  startnetvisble = (text, i) => {
    if (text['状态'] == '启动成功' || i == '启动成功') return;
    this.setState({
      visiblestartnet: true,
      textdatanet: text
    });
  }
  onChangeRadio = (e) => {
    this.setState({
      value: e.target.value,
    });
  }
  getData = (page, limit = this.state.limit, changeOrgid = this.props.changeOrgid, clickNetwork = this.props.clickNetwork, orgname) => {
    const $this = this;
    this.setState({
      message: 'loading'
    });
    const Token = localStorage.getItem('token');

    axios({
      method: 'get',
      url: '/api/block/network/queryBaasNetworkOrgApprove',
      headers: {
        'Content-Type': 'application/json',
        Authorization: Token
      },
      params: { 'page': page, limit: limit, orgId: changeOrgid, networkName: clickNetwork, orgName: orgname }
    })
      .then(function (response) {
        if ($this.ismounted) {
          var code = response.data.code;
          // if (statuscode[response.data.code] == undefined) code = '500'
          var message = statuscode[code];
          let data = [];
          response.data && response.data.data && response.data.data.rows && response.data.data.rows.forEach((e, i) => {
            var updTime = (((e.approveStatus) != 1000) && ((e.approveStatus) != 1010)) ? '' : e.updTime;
            data.push({
              key: String(i),
              组织名称: e.orgName,
              网络: e.networkName,
              状态: networkstatus[e.approveStatus],
              申请提交时间: e.submitTime,
              审批完成时间: updTime,
              applyId: e.applyId
            });
          });
          $this.setState({
            data: data,
            totalnum: response.data && response.data.data && response.data.data.total ? response.data.data.total : 0,
            totaldata: response.data && response.data.data && response.data.data.rows ? response.data.data.rows : [],
            message: message
          }, () => {
            setTimeout(() => {
              $this.setState({
                message: '',
              });
            }, 1000);
          });
        }
      })
      .catch(function (error) {
        console.log(error);
        if ($this.ismounted) {
          $this.setState({
            message: '请求失败，请刷新重试'
          }, () => {
            setTimeout(() => {
              $this.setState({
                message: '',
              });
            }, 1000);
          });
        }
      });
  }

  render() {
    return (
      <div>
        <Bread bread={['网络管理', ['网络管理', 'net'], ['审批记录', '/net/ApprovalRecord']]} />
        <div className="tabBox">
          <div className="inviteUserBox">
            <Input placeholder="请输入组织名称" className="input" onChange={this.searchchange} />
            <Button type="primary" className="search" onClick={this.search}><img src={require('../../../static/img/search_icon.png')} /></Button>
          </div>
          {/* <Button type="primary" className="inviteBtn" onClick={this.inviteshowModal}>邀请新组织</Button> */}
        </div>
        <Table
          columns={this.columnsInvite}
          dataSource={this.state.data}
          bordered
          pagination={false}
          onChange={this.handleChange}
        />
        <div className="page_foot">
          <span className="data_num">共{this.state.totalnum}条</span>
          <Pagination
            pageSizeOptions={this.setData.page}
            className="page"
            showSizeChanger
            showQuickJumper
            onShowSizeChange={this.onShowSizeChange}
            defaultCurrent={1}
            total={this.state.totalnum}
            onChange={this.onChange}
          />
        </div>
        <Invite
          visible={this.state.invitevisible}
          onCancel={this.invitehandleChancel}
          update={1}
          invitationdata={this.state.invitationdata}
        />
        <Detail
          visible={this.state.detailvisible}
          stop={this.stopnetvisble}
          title={this.state.title}
          start={this.startnetvisble}
          onCancel={this.detailhandleChancel}
          detaildata={this.state.detaildata}
          inviteshowModal={this.inviteshowModal}
        />
        <Approvaldetail
          visible={this.state.approvaldetailvisible}
          onCancel={this.approvaldetailhandleChancel}
          pass={this.handleComfirm.bind(this, this.state.textdata)}
          reject={this.handleRefuse.bind(this, this.state.textdata)}
          detailhandleChancel
          title={this.state.title}
          approvaldetaildata={this.state.approvaldetaildata}
          approvaledstatus={this.state.approvaledstatus}
        />
        <Tips message={this.state.message} />
        <Modal style={{ 'zIndex': 1000 }}
          visible={this.state.visiblepass}
          closable={false}
          title="提示"
          iconType="warning"
          onCancel={this.handleCancel}
          footer={[
            <Button key="back" onClick={this.handleCancel}>取消</Button>,
            <Button key="submit" type="primary" onClick={this.pass}>
              确定
            </Button>,
          ]}
        >
          <p className="textAlign_D">
            <span className="CommonTips">您是否确认通过组织：</span>
            <span className="userName"> {this.state.textdata ? this.state.textdata['组织名称'] : ''} 的申请</span>
          </p>
        </Modal>
        <Modal style={{ 'zIndex': 1000 }}
          closable={false}
          visible={this.state.visiblereject}
          title="提示"
          iconType="warning"
          onCancel={this.handleCancel}
          footer={[
            <Button key="back" onClick={this.handleCancel}>取消</Button>,
            <Button key="submit" type="primary" onClick={this.reject}>
              确定
            </Button>,
          ]}
        >
          <p className="textAlign_D">
            <span className="CommonTips">您是否确认拒绝组织：</span>
            <span className="userName"> {this.state.textdata ? this.state.textdata['组织名称'] : ''} 的申请</span>
          </p>
        </Modal>
        <Modal style={{ 'zIndex': 1000 }}
          closable={false}
          visible={this.state.visiblestartnet}
          title="提示"
          iconType="warning"
          onCancel={this.handleCancel}
          footer={[
            <Button key="back" onClick={this.handleCancel}>取消</Button>,
            <Button key="submit" type="primary" onClick={this.start}>
              确定
            </Button>,
          ]}
        >
          <p className="textAlign_D">
            <span className="CommonTips">您是否确认开启网络：{this.state.textdata ? this.state.textdata : ''}</span>
            {/* <span className="userName"> {this.state.textdata ? this.state.textdata['组织名称'] : ''} 的申请</span> */}
          </p>
        </Modal>
        <Modal style={{ 'zIndex': 1000 }}
          closable={false}
          visible={this.state.visiblestopnet}
          title="提示"
          iconType="warning"
          onCancel={this.handleCancel}
          footer={[
            <Button key="back" onClick={this.handleCancel}>取消</Button>,
            <Button key="submit" type="primary" onClick={this.stop}>
              确定
            </Button>,
          ]}
        >
          <p className="textAlign_D">
            <span className="CommonTips">您是否确认停止网络：{this.state.textdatanet ? this.state.textdatanet.networkName : ''}</span>
            <span className="userName"> {this.state.textdatanet ? this.state.textdatanet : ''} </span>
          </p>
        </Modal>
      </div>
    );
  }
}

export default connect((state) => {
  return { ...state };
})(ApprovalRecord);
